<template>
  <div class="asset-edit-page">
    <van-nav-bar
      :title="assetTypeMap[assetType] + '账户编辑'"
      left-arrow
      @click-left="onClickLeft"
      :style="{ backgroundColor: '#FFD847' }"
    />
    
    <van-form @submit="onSubmit" class="van-form">
      <van-cell-group inset>
        <van-field
          v-model="formData.name"
          name="name"
          label="账户名称"
          placeholder="请输入账户名称"
          :rules="[{ required: true, message: '请填写账户名称' }]"
        />
        <van-field
          v-model="formData.money"
          type="digit"
          name="money"
          :label="assetType === 7 ? '负债金额' : '账户余额'"
          :placeholder="assetType === 7 ? '请输入负债金额（输入正数）' : '请输入账户余额'"
          :rules="[
            { required: true, message: assetType === 7 ? '请填写负债金额' : '请填写账户余额' },
            { validator: validateMoney, message: '金额不能为负数' }
          ]"
        />
        <van-field
          v-model="formData.remark"
          name="remark"
          label="备注"
          placeholder="请输入备注信息（选填）"
        />
      </van-cell-group>
      
      <div style="margin: 16px;">
        <van-button
        class="submit-button"
        round block type="primary" 
        native-type="submit" 
        :loading="loading">
          保存修改
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showSuccessToast } from 'vant';
import { updateProperty } from '@/api/index';

const router = useRouter();
const route = useRoute();
const loading = ref(false);

// 资产类型
const assetType = ref(1);
const assetId = ref('');

// 资产类型映射（添加负债类型）
const assetTypeMap = {
  1: '现金',
  2: '储蓄卡',
  3: '信用卡',
  4: '支付宝',
  5: '微信',
  6: '其他',
  7: '负债'
};

// 表单数据（不需要 userId，后端会从 token 中获取）
const formData = reactive({
  name: '',
  money: '',
  remark: '', 
  type: assetType.value // 动态设置类型，根据选择的资产类型
});

// 验证余额（负债类型提示输入正数，其他类型不能为负）
const validateMoney = (val) => {
  return Number(val) >= 0;
};

// 获取路由参数
onMounted(() => {
  if (route.query.id) {
    assetId.value = route.query.id;
  }
  
  if (route.query.type) {
    assetType.value = Number(route.query.type);
    formData.type = Number(route.query.type);
  }
  
  if (route.query.name) {
    formData.name = route.query.name;
  }
  
  if (route.query.money) {
    // 如果是负债类型且金额为负数，转为正数显示
    let money = Number(route.query.money);
    if (assetType.value === 7 && money < 0) {
      money = Math.abs(money);
    }
    formData.money = String(money);
  }
  
  if (route.query.remark) {
    formData.remark = route.query.remark;
  }
});

// 提交表单
const onSubmit = async () => {
  try {
    loading.value = true;
    
    // 构建请求数据
    let money = Number(formData.money);
    
    // 如果是负债类型（type=7），将金额转为负数
    if (formData.type === 7 && money > 0) {
      money = -money;
    }
    
    const data = {
      name: formData.name,
      type: formData.type,
      money: money,
      remark: formData.remark
    };
    
    console.log('更新资产数据:', data);
    
    await updateProperty(assetId.value, data);
    showSuccessToast('修改成功');
    router.replace('/asset');
  } catch (error) {
    console.error('修改资产出错:', error);
    showToast(error.message || '修改资产出错');
  } finally {
    loading.value = false;
  }
};

// 返回按钮点击事件
const onClickLeft = () => {
  router.back();
};
</script>

<style scoped>
.asset-edit-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20px;
}
.van-form { 
  margin-top: 10px;
}

/* 导航栏样式 */
:deep(.van-nav-bar) {
  .van-nav-bar__title {
    color: #333;
    font-weight: bold;
  }
  
  /* 返回箭头样式 */
  .van-nav-bar__arrow {
    color: #333;
    font-size: 18px;
    font-weight: 600;
  }
}

/* 按钮样式 - 黄色主题 */
:deep(.submit-button) {
  background: linear-gradient(135deg, #FFD847 0%, #FFC107 100%);
  border: none;
  color: #333;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(255, 216, 71, 0.3);
  
  &:active {
    background: linear-gradient(135deg, #FFC107 0%, #FFB300 100%);
  }
}
</style>